package com.example.externalstoragedemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "666";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        save("file1.txt", "内容\nasrg是德国撒大噶发工具");
        Log.i(TAG, read("file1.txt"));
    }

    private void save(String fileName, String content) {
        // 获取外部存储的状态
        String externalStorageState = Environment.getExternalStorageState();

        // 设备已挂载
        if (Environment.MEDIA_MOUNTED.equals(externalStorageState)) {

            // 申请权限
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 1111);

            // 获取路径（sdk29以上不能用这个函数，好像要用Environment.getExternalFilesDir
            File sdPath = Environment.getExternalStorageDirectory();
            Log.i(TAG, sdPath.getAbsolutePath());  // /storage/emulated/0

            File file = new File(sdPath, fileName);

            FileOutputStream fileOutputStream = null;

            try {
                fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(content.getBytes());
                Log.i(TAG, "保存成功");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private String read(String fileName) {
        // 获取外部存储的状态
        String externalStorageState = Environment.getExternalStorageState();

        // 设备已挂载
        if (Environment.MEDIA_MOUNTED.equals(externalStorageState)) {

            // 申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2222);

            // 获取路径（sdk29以上不能用这个函数，好像要用Environment.getExternalFilesDir
            File sdPath = Environment.getExternalStorageDirectory();
            Log.i(TAG, sdPath.getAbsolutePath());  // /storage/emulated/0

            File file = new File(sdPath, fileName);

            FileInputStream fileInputStream = null;
            BufferedReader bufferedReader = null;

            try {
                fileInputStream = new FileInputStream(file);
                // 也可以不用BufferedReader，获取available，通过byte数组读取
                bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

                return bufferedReader.readLine();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 关闭
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "没有";
    }

    /**
     * 重写权限处理回调函数
     * @param requestCode 请求码
     * @param permissions 请求的权限
     * @param grantResults 通过的请求
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1111) {
            for (int i = 0; i < permissions.length; i++) {
                if ("android.permission.WRITE_EXTERNAL_STORAGE".equals(permissions[i]) &&
                        grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "权限申请通过");
                }
            }
        }
    }
}